import 'package:get/get.dart';
import 'package:trollee/app/core/constants/storage.dart';
import 'package:trollee/app/core/utils/utils.dart';
import 'package:trollee/app/data/entities/user/user_entity.dart';
import 'package:trollee/app/routes/app_pages.dart';

abstract class UserManager {
  static void init() {
    _isLoggedIn = getToken() != null && getUser() != null;
  }

  /// 用户信息, 可利用 ObxValue 监听数据变化
  static final _userEntity = Rxn<UserEntity>();

  static String? _token;

  static late bool _isLoggedIn;

  static Rxn<UserEntity> get rxUserEntity => _userEntity;

  /// 是否登录了
  static bool get isLoggedIn => _isLoggedIn;

  /// 退出登录，清空缓存数据
  static void logout() {
    AppLogger.log('[UserManager.logout()] 退出登录，清除用户信息');
    removeUserInfo();
  }

  /// 清除和重置相关用户数据
  static void removeUserInfo() {
    _isLoggedIn = false;
    _token = null;
    _userEntity.value = null;
    StorageUtil.removeAll([StorageConstants.userInfo, StorageConstants.authenticationToken]);
    Get.offAllNamed(AppRoutes.authLogin);
  }

  /// 清除token
  static void removeToken() {
    StorageUtil.removeAll([StorageConstants.authenticationToken]);
  }

  /// 进行登录
  static void login(UserEntity userEntity) {
    _isLoggedIn = true;
    _userEntity.trigger(userEntity);
    // saveUser(userEntity).whenComplete(() {
      // ... 继续其他设置, 例如埋点
    // });
    // EventBusUtil.emit(LoginSuccessEvent());
  }

  static Future<void> saveUser(UserEntity userEntity) async {
    _userEntity.trigger(userEntity);
    await StorageUtil.setJSON(StorageConstants.userInfo, userEntity.toJson());
  }

  static UserEntity? getUser() {
    _userEntity.value ??= StorageUtil.getEntity<UserEntity>(StorageConstants.userInfo);
    return _userEntity.value;
  }

  static Future<void> saveToken(String? token) async {
    if(token != null) {
      _token = token;
      await StorageUtil.setString(StorageConstants.authenticationToken, token);
    }
  }

  static String? getToken() {
    _token ??= StorageUtil.getString(StorageConstants.authenticationToken);
    return _token;
  }

  /// 调用网络接口请求用户信息
  static Future<bool> requestUserInfo() async {
    // 请求接口
    // 保存用户信息
    return true;
  }

  static getUserId() {
    return _userEntity.value?.userId ?? 0;
  }

  static bool isCurrentUser(int userId) => getUserId() == userId;

}
